package login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ResourceBundle;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    static String trueUsername;
    static String truePassword;

    static {
        ResourceBundle user = ResourceBundle.getBundle("user");
        trueUsername = user.getString("username");
        truePassword = user.getString("password");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println("cookie:");
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println(name + ":" + value);
        }


        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //校验验证码：
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("checkCode");
        String checkCode = req.getParameter("checkCode");
        //校验失败，刷新界面

        if (code.equals(checkCode)) {
            System.out.println("校验成功");
            if (username.equals(trueUsername) && password.equals(truePassword)) {
                req.getRequestDispatcher("success").forward(req, resp);
            } else {
                req.getRequestDispatcher("fail").forward(req, resp);
            }

        } else if (!code.equals(checkCode)) {
            System.out.println("校验失败");
            //刷新界面
            resp.setHeader("refresh", "0.2;login.html");
        }
    }
}
